# from loggerconfig import logger

import csv,time
import matplotlib.pyplot as plt
import numpy as np

# 设置中文字体为黑体
plt.rcParams['font.family']='SimHei'
# 解决负号显示为方块的问题
plt.rcParams['axes.unicode_minus'] = False



def read_client_log(file):
    with open(file, 'r') as f:
        data = f.readlines()
        return data

interval_list,transfer_list,bitrate_list,retr_list,cwnd_list = [],[],[],[],[]
client_log = read_client_log('./log_from_client/cc')

def analyze_clinet_log(data):
    global interval_list,transfer_list,bitrate_list,retr_list,cwnd_list
    client_log_list = []
    start_end_list = []
    
    start_index,end_index = 0,0
    for index,value in enumerate(data):
        if "[ ID] Interval" in value:
            start_end_list.append(index)
            start_index = min(start_end_list)
            end_index = max(start_end_list)
        if index > start_index >0:
            if "- - - - " in value:
                break
            # print(value.split(" MBytes")[0].split("sec")[-1])
            transfer = float(value.split(" MBytes")[0].split("sec")[-1].strip(""))
            transfer_list.append(transfer)

            interval = float(value.split("sec")[0].split("-")[-1].strip(""))
            interval_list.append(interval)

            bitrate = float(value.split("Mbits/sec")[0].split("MBytes")[-1].strip(""))
            bitrate_list.append(bitrate)

            cwnd1 = (value.split("Bytes")[-2].split("sec")[-1].split(" "))
            cwnd_retr = []
            for i,j in enumerate(cwnd1):
                if j != "" and j.isalpha() == False:
                    cwnd_retr.append(i)

            cwnd = cwnd1[max(cwnd_retr)]+" "+cwnd1[-1]
            retr = int(cwnd1[min(cwnd_retr)])

            cwnd_list.append(cwnd)
            retr_list.append(retr)
    
analyze_clinet_log(client_log)

local_time_tuple = time.localtime()
formatted_time = time.strftime("%Y-%m-%dT%H-%M-%S", local_time_tuple)

# 传输速度
# 方差
mean_transfer = sum(transfer_list) / len(transfer_list)
variance_sum = 0
for i in transfer_list:
    variance_sum += (i - mean_transfer) ** 2
variance = variance_sum / len(transfer_list)
print("传输速度的方差为:", variance,"  传输速度的平均值:",mean_transfer)

# 画图
x1 = np.array(interval_list)
y1 = np.array(transfer_list)

plt.plot(x1, y1, color='r', linestyle='--')
plt.xlabel('时间 sec')
plt.ylabel('传输速度 MBytes')
plt.title('时间-传输速度图')
save_path = './img/{}-interval-transfer.jpg'.format(formatted_time)
plt.savefig(save_path)
plt.close()


# 带宽
# 方差
mean_bitrate = sum(bitrate_list) / len(bitrate_list)
variance_sum = 0
for i in bitrate_list:
    variance_sum += (i - mean_bitrate) ** 2
variance = variance_sum / len(bitrate_list)
print("带宽的方差为:", variance," 带宽的平均值:",mean_bitrate)

# 画图
x2 = np.array(interval_list)
y2 = np.array(bitrate_list)


plt.plot(x2, y2, color='r', linestyle='--')
plt.xlabel('时间 sec')
plt.ylabel('带宽 Mbits/sec')
plt.title('时间-带宽图')
save_path = './img/{}-interval-bitrate.jpg'.format(formatted_time)
plt.savefig(save_path)
plt.close()
